<?php

namespace app\client\services;

use app\admin\model\CustomerModel;
use app\admin\model\IncomeModel;
use app\admin\model\RedpacketModel;
use think\facade\Db;

class RedPacketService
{
    public static function getRedPacket($customerId){

        $date=date('Y-m-d');
        $res=RedpacketModel::detail([
            ['customer_id','=',$customerId],
            ['date','=',$date]
        ],'*');
        if($res) {
            if ($res->status == 0) {
                api_return(200, '', [
                    'is_receive' => 0,
                    'amount' => $res->amount
                ]);
            }else{
                api_return(200, '', [
                    'is_receive' => 1,
                    'amount' => 0
                ]);
            }
        }else {
            $params = [
                'customer_id' => $customerId,
                'date' => $date,
                'amount' => $amount = rand(1, 20),
                'status' => 0,

            ];
            $res=RedpacketModel::editWithReturn($params);
            if($res){
                api_return(200, '', [
                    'is_receive' => 0,
                    'amount' => $amount
                ]);
            }else
                api_return(500);
        }
    }
    public static function check($customerId){
        $date=date('Y-m-d');
        $info=RedpacketModel::detail([
            ['customer_id','=',$customerId],
            ['date','=',$date],
            ['status','=',0],
        ],'*');
        $info->status=1;
        Db::startTrans();
        $r=$info->save();
        if($r) {
            CustomerModel::setBalance($customerId, $info->amount, 2, $info->id);
            Db::commit();
            api_return(200);
        }
        else{
            Db::rolllback();
            api_return(500);
        }

    }
    public static function getLimit($customerId){
        $list= IncomeModel::countGroupByType($customerId);
        $limit=($list[1])??0*1.1+$list[3];
        return ($limit>0)?$limit:0;
    }
}
